import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../providers/task_provider.dart';
import '../providers/member_provider.dart';
import '../models/task.dart';
import '../models/member.dart';
import '../widgets/custom_window_frame.dart';

class AnalyticsScreen extends StatelessWidget {
  const AnalyticsScreen({super.key});

  @override
  Widget build(BuildContext context) {
    return CustomWindowFrame(
      title: '统计分析',
      child: Scaffold(
        appBar: AppBar(
          title: const Text('统计分析'),
          backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        ),
        body: Consumer2<TaskProvider, MemberProvider>(
          builder: (context, taskProvider, memberProvider, child) {
            final allTasks = taskProvider.tasks;
            final completedTasks = taskProvider.completedTasks;
            final pendingTasks = taskProvider.pendingTasks;

            // 计算任务完成率
            final completionRate = allTasks.isEmpty 
                ? 0.0 
                : (completedTasks.length / allTasks.length * 100);

            // 按优先级统计
            final highPriorityTasks = allTasks.where((t) => t.priority == TaskPriority.high).length;
            final mediumPriorityTasks = allTasks.where((t) => t.priority == TaskPriority.medium).length;
            final lowPriorityTasks = allTasks.where((t) => t.priority == TaskPriority.low).length;

            // 统计逾期任务
            final now = DateTime.now();
            final overdueTasks = pendingTasks.where((t) => 
              t.dueDate != null && t.dueDate!.isBefore(now)
            ).length;

            // 按成员统计
            final memberStats = _calculateMemberStats(allTasks, memberProvider);

            return ListView(
              padding: const EdgeInsets.all(16),
              children: [
                _buildStatCard(
                  title: '任务总览',
                  items: [
                    _StatItem('总任务数', allTasks.length),
                    _StatItem('已完成', completedTasks.length),
                    _StatItem('待办中', pendingTasks.length),
                    _StatItem('完成率', '${completionRate.toStringAsFixed(1)}%'),
                  ],
                ),
                const SizedBox(height: 16),
                _buildStatCard(
                  title: '优先级分布',
                  items: [
                    _StatItem('高优先级', highPriorityTasks),
                    _StatItem('中优先级', mediumPriorityTasks),
                    _StatItem('低优先级', lowPriorityTasks),
                  ],
                ),
                const SizedBox(height: 16),
                _buildStatCard(
                  title: '任务状态',
                  items: [
                    _StatItem('逾期任务', overdueTasks),
                    _StatItem('正常进行', pendingTasks.length - overdueTasks),
                  ],
                ),
                if (memberStats.isNotEmpty) ...[
                  const SizedBox(height: 16),
                  _buildMemberStats(memberStats),
                ],
                if (allTasks.isNotEmpty) ...[
                  const SizedBox(height: 16),
                  _buildRecentActivity(allTasks, memberProvider),
                ],
              ],
            );
          },
        ),
      ),
    );
  }

  List<_MemberStat> _calculateMemberStats(List<Task> tasks, MemberProvider memberProvider) {
    // 创建成员任务统计映射
    final Map<String, _MemberStat> statsMap = {};
    
    // 遍历所有任务
    for (final task in tasks) {
      if (task.assignedTo != null) {
        final member = memberProvider.getMemberById(task.assignedTo!);
        if (member != null) {
          if (!statsMap.containsKey(member.id)) {
            statsMap[member.id] = _MemberStat(
              member: member,
              totalTasks: 0,
              completedTasks: 0,
            );
          }
          
          statsMap[member.id]!.totalTasks++;
          if (task.isCompleted) {
            statsMap[member.id]!.completedTasks++;
          }
        }
      }
    }
    
    // 转换为列表并排序
    final statsList = statsMap.values.toList()
      ..sort((a, b) => b.totalTasks.compareTo(a.totalTasks));
    
    return statsList;
  }

  Widget _buildMemberStats(List<_MemberStat> memberStats) {
    return Card(
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            const Text(
              '成员统计',
              style: TextStyle(
                fontSize: 18,
                fontWeight: FontWeight.bold,
              ),
            ),
            const Divider(),
            ...memberStats.map((stat) {
              final completionRate = stat.totalTasks == 0 
                  ? 0.0 
                  : (stat.completedTasks / stat.totalTasks * 100);
              
              return ListTile(
                leading: CircleAvatar(
                  child: Text(stat.member.name[0]),
                ),
                title: Text(stat.member.name),
                subtitle: Text('总任务: ${stat.totalTasks} | 已完成: ${stat.completedTasks}'),
                trailing: Text(
                  '${completionRate.toStringAsFixed(1)}%',
                  style: TextStyle(
                    color: completionRate > 50 ? Colors.green : Colors.orange,
                    fontWeight: FontWeight.bold,
                  ),
                ),
              );
            }),
          ],
        ),
      ),
    );
  }

  Widget _buildRecentActivity(List<Task> tasks, MemberProvider memberProvider) {
    final recentTasks = tasks
        .take(5)
        .toList()
      ..sort((a, b) => b.createdAt.compareTo(a.createdAt));

    return Card(
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            const Text(
              '最近活动',
              style: TextStyle(
                fontSize: 18,
                fontWeight: FontWeight.bold,
              ),
            ),
            const Divider(),
            ...recentTasks.map((task) {
              final assignedMember = task.assignedTo != null 
                  ? memberProvider.getMemberById(task.assignedTo!)
                  : null;

              return ListTile(
                title: Text(
                  task.title,
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                ),
                subtitle: Text(
                  '创建于: ${task.createdAt.toString().split('.')[0]}'
                  '${assignedMember != null ? ' | 负责人: ${assignedMember.name}' : ''}',
                ),
                trailing: Icon(
                  task.isCompleted ? Icons.check_circle : Icons.pending,
                  color: task.isCompleted ? Colors.green : Colors.orange,
                ),
              );
            }),
          ],
        ),
      ),
    );
  }

  Widget _buildStatCard({
    required String title,
    required List<_StatItem> items,
  }) {
    return Card(
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              title,
              style: const TextStyle(
                fontSize: 18,
                fontWeight: FontWeight.bold,
              ),
            ),
            const Divider(),
            GridView.count(
              crossAxisCount: 2,
              shrinkWrap: true,
              childAspectRatio: 2.5,
              physics: const NeverScrollableScrollPhysics(),
              children: items.map((item) => _buildStatItem(item)).toList(),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildStatItem(_StatItem item) {
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        Text(
          item.value.toString(),
          style: const TextStyle(
            fontSize: 24,
            fontWeight: FontWeight.bold,
          ),
        ),
        Text(
          item.label,
          style: const TextStyle(
            color: Colors.grey,
          ),
        ),
      ],
    );
  }
}

class _StatItem {
  final String label;
  final dynamic value;

  _StatItem(this.label, this.value);
}

class _MemberStat {
  final Member member;
  int totalTasks;
  int completedTasks;

  _MemberStat({
    required this.member,
    this.totalTasks = 0,
    this.completedTasks = 0,
  });
} 